'use strict'

let globalObject = require('./globalobject')
let RootServer = require('../distributed/rootserver')
let NodeClient = require('../distributed/nodeclient')

//抽象出的一个服务进程
class FFServer {
  constructor() {
    this.root = null
    this.remote = {}
    this.master_remote = null
    this.servername = null
    this.remoteportlist = []
    this.rootport = null
    this.masterClient = null
    this.globalObject = globalObject
    globalObject.server = this
  }


  initconfig(config, servername, dbconfig, memconfig, masterconf) {
    globalObject.json_config = config
    this.rootport = config['rootport'] //root节点配置
    this.remoteportlist = config['remoteport']

    this.servername = servername ? servername : config['name']

    if (this.rootport) {
      this.rootserver = new RootServer(this.servername)
      globalObject.rootserver = this.rootserver
      this.rootserver.createServer(this.rootport) //创建节点服务器
    }
    /**/
    if (this.remoteportlist) {
      for (let cnf of this.remoteportlist) {
        let rname = cnf['rootname']
        this.remote[rname] = new NodeClient(this.servername)
      }
    }

    if (masterconf) {
      let masterport = masterconf['rootport']
      let masterhost = masterconf['roothost']
      this.masterClient = new NodeClient(this.servername)
      this.masterClient.connect(masterport, '127.0.0.1') //连接master服务器
      globalObject.masterClient = this.masterClient
    }

    /*
				if (app) {
					require(app)
				}
		    */
  }

  //启动服务器
  start() {
    globalObject.masterRemote('remoteConnect', function(transport, msg, next) {
      let rootname = msg.rootname
      for (let cnf of globalObject.server.remoteportlist) {
        if (rootname === cnf['rootname']) {
          let rootport = cnf['rootport']
          globalObject.server.remote[rootname].connect(rootport, '127.0.0.1')
          break
        }
      }
    }) /**/
  }

}

module.exports = FFServer
